package com.fgchen.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * Created by Administrator on 2018-04-08.
 */
@Configuration
@MapperScan(basePackages = "com.fgchen.mapper.study01", sqlSessionFactoryRef = "study01SqlSessionFactory")
public class AppConfig_Study01 {

    @Bean(name = "study01DataSource")
    @Primary
    @ConfigurationProperties(prefix = "spring.datasource.study01")
    public DataSource dataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "study01SqlSessionFactory")
    @Primary
    public SqlSessionFactory sqlSessionFactory() throws Exception {
        SqlSessionFactoryBean ssfb = new SqlSessionFactoryBean();
        ssfb.setDataSource(this.dataSource());
        /*ssfb.setMapperLocations(
                new PathMatchingResourcePatternResolver().getResources(
                        "classpath:mapper/study01*//*.xml"
                )
        );*/
        return ssfb.getObject();
    }

    @Bean(name = "study01TransactionManager")
    @Primary
    public DataSourceTransactionManager transactionManager() {
        return new DataSourceTransactionManager(this.dataSource());
    }

    @Bean(name = "study01SqlSessionTemplate")
    @Primary
    public SqlSessionTemplate sqlSessionTemplate() throws Exception {
        return new SqlSessionTemplate(this.sqlSessionFactory());
    }

}
